library(tidyverse)

x <- c(1, 1, 2, 2, 2)

# rank, ties are coerced into unique
row_number(x)
# ties get smallest value and leave gap
min_rank(x)
# no gap after ties
dense_rank(x)
# gives the proportion of values <= x_i
cume_dist(x)
# counts the total number of values < x_i, and divides it by total_count - 1
percent_rank(x)

# in use: select top 10% value for each group
starwars |>
  group_by(sex) |>
  filter(cume_dist(height) > .9)

# ntile to coarsely group ranks
starwars |>
  mutate(height_tile = ntile(height, 4)) |>
  group_by(height_tile) |>
  summarise(mean(height))

# use lead() or lag() to find difference along vector
economics |>
  mutate(unemploy_delta = unemploy - lag(unemploy))
